package com.sanhe.rfmuscle.activity.work;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.menu.app.MyApp;
import com.menu.app.db.WarnDao;
import com.menu.app.event.work.HandleSetEvent;
import com.menu.app.event.work.TempEvent;
import com.menu.app.http.bean.ReportBean;
import com.menu.app.http.req.WarnReportReq;
import com.menu.app.it.ReqCallback;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;
import com.sanhe.rfmuscle.R;
import com.sanhe.rfmuscle.databinding.ActivityWarnBinding;
import com.sanhe.rfmuscle.event.Event;
import com.sanhe.rfmuscle.event.FlowStateEvent;
import com.sanhe.rfmuscle.event.LevelStateEvent;
import com.sanhe.rfmuscle.event.TempStateEvent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

public class WarnActivity extends BaseWorkActivity {

    ActivityWarnBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityWarnBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.back.setOnClickListener(v -> sendTouchEvent((byte) 1, (byte) 0x20));

        updateTv();
        updateFlow();
        updateTemp();
        updateLevel();
        updateReq();
        updateTemperature();

        stopWork();
    }

    private void updateTemperature() {
        binding.temp.setText(Event.tempEvent.getValue() + "°C");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(HandleSetEvent event) {
        updateTv();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(FlowStateEvent event) {
        updateFlow();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TempStateEvent event) {
        updateTemp();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LevelStateEvent event) {
        updateLevel();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TempEvent event) {
        updateTemperature();
    }


    private void updateFlow() {
        if (Event.flowStateEvent.getValue() == 1) {
            binding.warnFlow.setVisibility(View.VISIBLE);
        } else {
            binding.warnFlow.setVisibility(View.INVISIBLE);
        }
    }

    private void updateTemp() {
        if (Event.tempStateEvent.getValue() != 0) {
            binding.warnTemp.setBackgroundResource(R.drawable.warn_red_stroke);
            binding.tmpImg.setVisibility(View.VISIBLE);
        } else {
            binding.warnTemp.setBackgroundResource(R.drawable.warn_white_stroke);
            binding.tmpImg.setVisibility(View.INVISIBLE);
        }
    }

    private void updateLevel() {
        if (Event.levelStateEvent.getValue() == 1) {
            binding.warnLevel.setVisibility(View.VISIBLE);
        } else {
            binding.warnLevel.setVisibility(View.INVISIBLE);
        }
    }

    private void updateTv() {
        if (Event.handleSetEvent.getValue() == 1) {
            binding.tv.setVisibility(View.VISIBLE);
        } else {
            binding.tv.setVisibility(View.INVISIBLE);
        }
    }

    String lastError = null;
    long errorTime = 0;

    private void updateReq() {
        HashMap<String, String> map = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        if (Event.flowStateEvent.getValue() == 1 || Event.handleSetEvent.getValue() == 1) {
            sb.append("1,");
        }
        if (Event.tempStateEvent.getValue() != 0) {
            sb.append("2,");
        }
        if (Event.levelStateEvent.getValue() == 1) {
            sb.append("3,");
        }
        String tmp = sb.toString();
        if (tmp.isEmpty()) {
            sb.append("2,");
            tmp = sb.toString();
        }
        long time = System.currentTimeMillis();
        tmp = tmp.substring(0, tmp.length() - 1);
        if (tmp.equals(lastError) && time - errorTime < 5 * 60000) {
            return;
        }
        errorTime = System.currentTimeMillis();
        lastError = tmp;
        HashMap param = new HashMap();
        param.put("error", lastError);
        param.put("temp", Event.tempEvent.getValue() + "");
        param.put("time", System.currentTimeMillis());
        if (MyApp.getApp().getDoc() != null) {
            param.put("customId", MyApp.getApp().getDoc().serverId);
        }
        new WarnReportReq(param, null).req(new ReqCallback<ReportBean>() {
            @Override
            public void callback(boolean success, ReportBean bean) {
                if (success && bean.isValid()) {
                    Log.e(TAG, "Warn callback: success");
                } else {
                    Log.e(TAG, "Warn callback: failed");
                    new WarnDao().insert(map, null);
                }
            }
        });
    }

    private void stopWork() {
        TaskEngine.getInstance().submit(new SilentTask("stopWork") {
            @Override
            public void runInBackground() throws Exception {
                Thread.sleep(1000);
                if (Event.p2WorkEvent.getValue() == 1) {
                    sendTouchEvent((byte) 0, (byte) 0x2d);
                    Thread.sleep(200);
                }
                if (Event.p1WorkEvent.getValue() == 1) {
                    sendTouchEvent((byte) 0, (byte) 0x2c);
                }
            }
        });
    }
}
